package com.md.youyouhui.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


import com.md.youyouhui.R;
import com.md.youyouhui.databinding.AdapterUserBinding;
import com.md.youyouhui.databinding.FragemtnUserBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.NetWorkConstant;
import com.md.youyouhui.net.response.CouponResponse;
import com.md.youyouhui.net.response.UserInfoResponse;
import com.md.youyouhui.ui.BaseFragment;
import com.md.youyouhui.ui.adapter.DataBoundViewHolder;
import com.md.youyouhui.ui.home.QuestionMoreActivity;
import com.md.youyouhui.ui.home.WebNewsActivity;
import com.md.youyouhui.ui.login.LoginActivity;
import com.md.youyouhui.ui.shopping.AddressMangerActivity;
import com.md.youyouhui.ui.user.AboutUserActivity;
import com.md.youyouhui.ui.user.CouponUserActivity;
import com.md.youyouhui.ui.user.OilUserCardActivity;
import com.md.youyouhui.ui.user.OrderInfoListActivity;
import com.md.youyouhui.ui.user.OrderInfoShoppingActivity;
import com.md.youyouhui.ui.user.UserSafeActivity;
import com.md.youyouhui.utils.DialogLoginUtils;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;

import java.util.List;

/**
 * Created by AdministratorZJ
 * on 2019/4/8.
 */
public class UserFragment extends BaseFragment {
    private String[] title = {"商品订单", "领卡订单", "优惠券", "地址管理", "问题解答", "客服中心", "关于我们","隐私协议"};
    private String[] content = {"", "", "可用0张", "地址管理", "有问题点这里", "17816209959(工作日09:00-17:30)", "了解更多信息",""};
    private int[] icon = {R.drawable.mallcheck, R.drawable.cardcheck, R.drawable.coupons, R.drawable.address, R.drawable.question, R.drawable.customerservice, R.drawable.aboutus,R.drawable.question};
    private FragemtnUserBinding userBinding;
    private MainViewModel viewModel;
    private MyAdapter adapter;
    private int couponNum;
    private String token;
    String show ;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        userBinding = DataBindingUtil.inflate(inflater, R.layout.fragemtn_user, container, false);
        viewModel = new MainViewModel();
        show = SharedPreferencesUtils.getString(mActivity, Constants.IS_SHOW, "");
        if("0".equals(show)){
            userBinding.oilLayout.setVisibility(View.GONE);
            userBinding.payLayout.setVisibility(View.GONE);
        }
        initData();
        return userBinding.getRoot();
    }

    private void initData() {
        userBinding.userLayout.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                startActivity(new Intent(mActivity, LoginActivity.class));
            } else {
                startActivity(new Intent(mActivity, UserSafeActivity.class));
            }
        });
        userBinding.oilLayout.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(mActivity);
                return;
            }
            startActivity(new Intent(mActivity, OilUserCardActivity.class));
        });
        userBinding.payLayout.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(mActivity);
                return;
            }
            startActivity(new Intent(mActivity, OrderInfoListActivity.class));
        });
        adapter = new MyAdapter();
        userBinding.userRecycler.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        token = SharedPreferencesUtils.getString(mActivity, Constants.USER_TOKEN, "");
        if (TextUtils.isEmpty(token)) {
            return;
        }
        getUserInfo();
        getCoupon();
    }

    private void getUserInfo() {
        viewModel.getUserInfo().observe(this, userInfoResponse -> {
            assert userInfoResponse != null;
            switch (userInfoResponse.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    UserInfoResponse data = userInfoResponse.data;
                    if (null == data) {
                        return;
                    }
                    userBinding.userId.setText(String.format("账号:%s", data.mobile));
                    userBinding.userOilNum.setText(String.format("%s张", data.oilCardCount));
                    userBinding.userPrice.setText(String.format("%s元", data.recentTopUpAmount));
                    couponNum = Integer.parseInt(data.couponCount);
                    adapter.notifyDataSetChanged();
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, userInfoResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void getCoupon() {
        //0未使用，1已使用，2已过期0 0
        viewModel.getCoupon(1, 100, 0).observe(this, couponResponse -> {
            assert couponResponse != null;
            switch (couponResponse.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    CouponResponse data = couponResponse.data;
                    if (null == data) {
                        return;
                    }
                    List<CouponResponse.Rows> rows = data.rows;
                    adapter.notifyDataSetChanged();
                    break;
                case ERROR:
                    ToastUtils.errMake(mActivity, couponResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<DataBoundViewHolder<AdapterUserBinding>> {

        @NonNull
        @Override
        public DataBoundViewHolder<AdapterUserBinding> onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            AdapterUserBinding userBinding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.adapter_user, viewGroup, false);
            return new DataBoundViewHolder<>(userBinding);
        }

        @Override
        public void onBindViewHolder(@NonNull DataBoundViewHolder<AdapterUserBinding> holder, int i) {
            holder.binding.userReIcon.setImageResource(icon[i]);
            holder.binding.userTitle.setText(title[i]);
            if (i == 2) {
                holder.binding.userContent.setText(String.format("%s张", couponNum));
            } else {
                holder.binding.userContent.setText(content[i]);
            }
            holder.itemView.setOnClickListener(v -> {
                if (i == 0) {
                    if (TextUtils.isEmpty(token)) {
                        new DialogLoginUtils().dialogLogin(mActivity);
                        return;
                    }
                    startActivity(new Intent(mActivity, OrderInfoShoppingActivity.class).putExtra("title", "商品订单").putExtra("type", 0));
                } else if (i == 1) {
                    if (TextUtils.isEmpty(token)) {
                        new DialogLoginUtils().dialogLogin(mActivity);
                        return;
                    }
                    startActivity(new Intent(mActivity, OrderInfoShoppingActivity.class).putExtra("title", "领卡订单").putExtra("type", 1));
                } else if (i == 2) {
                    if (TextUtils.isEmpty(token)) {
                        new DialogLoginUtils().dialogLogin(mActivity);
                        return;
                    }
                    startActivity(new Intent(mActivity, CouponUserActivity.class));
                } else if (i == 3) {
                    if (TextUtils.isEmpty(token)) {
                        new DialogLoginUtils().dialogLogin(mActivity);
                        return;
                    }
                    startActivity(new Intent(mActivity, AddressMangerActivity.class).putExtra("check", true));
                } else if (i == 4) {
                    startActivity(new Intent(mActivity, QuestionMoreActivity.class));
                } else if (i == 5) {
                    call("17816209959");
                    //startActivity(new Intent(mActivity, BannerShareActivity.class).putExtra("imageId", R.drawable.share_user));
                } else if (i == 6) {
                    //startActivity(new Intent(mActivity, BannerViewActivity.class).putExtra("imageId", R.drawable.user_about));
                    startActivity(new Intent(mActivity, AboutUserActivity.class));
                }
                else if (i == 7) {
                    //http://www.youyouhuiyk.com:9512/api/invited/
                    //隐私协议
                    //startActivity(new Intent(mActivity, BannerViewActivity.class).putExtra("imageId", R.drawable.user_about));
                    startActivity(new Intent(mActivity, WebNewsActivity.class).putExtra("url", NetWorkConstant.BASE_URL_HTTP+"9512/api/invited/privateagreement"));
                }

            });
        }

        @Override
        public int getItemCount() {
            return icon.length;
        }
    }


    private void call(String tel) {
        new AlertDialog.Builder(mActivity)
                .setMessage("确定拨打" + tel + "此号码")
                .setNegativeButton("取消", (dialog, which) -> {
                })
                .setPositiveButton("确定", (dialog, which) -> {
                    requestCallPhone(tel);
                }).show();
    }

    private void requestCallPhone(String tel) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                UserFragment.this.requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1);
            } else {
                callPhone(tel);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int grantResult = grantResults[i];
                if (permission.equals(Manifest.permission.CALL_PHONE)) {
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
                        callPhone("");
                    } else {
                        Toast.makeText(mActivity, "电话相关权限没有打开", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }

    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNum 电话号码
     */
    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }
}
